import { omit } from 'lodash';

const defaultState = {
    // 目录结构
    tree: {
        name: 'swagger',
        type: 'dir',
        children: [],
        size: 0
    },

    // 已展开的节点
    expanded: {}
};

/**
 * 读取目录信息
 * @type {String}
 */
export const LOAD_DIR = 'LOAD_DIR';

/**
 * 展开目录
 * @type {String}
 */
export const EXPAND_DIR = 'EXPAND_DIR';

/**
 * 收起目录
 * @type {String}
 */
export const COLLAPSE_DIR = 'COLLAPSE_DIR';

/**
 * 将 [ 'a', 'b' ] 转换为 { a: true, b: true }
 * @param  {string[]} array
 * @return {Object}
 */
export function arrayToProps(array) {
    const props = {};

    array.forEach(item => {
        props[item] = true;
    });

    return props;
}

/**
 * Swagger 目录信息
 * @param {Object} state
 * @param {Object} action
 */
export default function fileReducer(state = defaultState, action) {
    switch (action.type) {
        case `${LOAD_DIR}_FULFILLED`:
            return {
                ...state,
                tree: action.payload,
                expanded: {}
            };
        case EXPAND_DIR:
            return {
                ...state,
                expanded: {
                    ...state.expanded,
                    ...action.payload
                }
            };
        case COLLAPSE_DIR:
            return {
                ...state,
                expanded: omit(state.expanded, action.payload)
            };
        default:
            return state;
    }
}